package com.cloudweb.oa.controller;


import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.StrUtil;
import cn.js.fan.web.Global;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloudweb.oa.entity.UserPlanAttachment;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.service.IFileService;
import com.cloudweb.oa.service.IUserPlanAttachmentService;
import com.cloudweb.oa.thread.PreviewGenerateThread;
import com.cloudweb.oa.utils.FileUtil;
import com.cloudweb.oa.utils.PreviewUtil;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.kit.util.FileUpload;
import com.redmoon.oa.Config;
import com.redmoon.oa.message.Attachment;
import com.redmoon.oa.message.MessageDb;
import com.redmoon.oa.message.MessageMgr;
import com.redmoon.oa.person.PlanDb;
import com.redmoon.oa.person.PlanMgr;
import com.redmoon.oa.pvg.Privilege;
import com.redmoon.oa.util.Pdf2Html;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fgf
 * @since 2024-06-05
 */
@RestController
@RequestMapping("/plan/attachment")
public class UserPlanAttachmentController {

    @Autowired
    IUserPlanAttachmentService userPlanAttachmentService;

    @Autowired
    IFileService fileService;

    @Autowired
    AuthUtil authUtil;

    @Autowired
    HttpServletRequest request;

    @ApiOperation(value = "上传文件", notes = "上传文件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "MultipartFile"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> upload(@RequestParam(value = "file") MultipartFile file) {
        // 置保存路径
        Calendar cal = Calendar.getInstance();
        String year = "" + (cal.get(Calendar.YEAR));
        String month = "" + (cal.get(Calendar.MONTH) + 1);

        String vpath = "upfile/plan/" + year + "/" + month + "/";

        String name = file.getOriginalFilename();
        String ext = StrUtil.getFileExt(name);
        String diskName = FileUpload.getRandName() + "." + ext;
        boolean canPreview = false;
        String previewUrl = "";

        UserPlanAttachment userPlanAttachment = new UserPlanAttachment();
        userPlanAttachment.setPlanId(0);
        userPlanAttachment.setCreateDate(DateUtil.toLocalDateTime(new Date()));
        userPlanAttachment.setDiskName(diskName);
        userPlanAttachment.setVisualPath(vpath);
        userPlanAttachment.setFileSize(file.getSize());
        userPlanAttachment.setName(file.getOriginalFilename());
        boolean re = userPlanAttachment.insert();
        if (re) {
            try {
                fileService.write(file, vpath, diskName);

                Config cfg = Config.getInstance();
                boolean canOfficeFilePreview = cfg.getBooleanProperty("canOfficeFilePreview");
                boolean canPdfFilePreview = cfg.getBooleanProperty("canPdfFilePreview");
                // 生成预览
                boolean isGenPreview = false;
                if (canOfficeFilePreview) {
                    if (FileUtil.isOfficeFile(diskName)) {
                        isGenPreview = true;
                    }
                }
                if (canPdfFilePreview) {
                    if ("pdf".equals(ext)) {
                        isGenPreview = true;
                    }
                }

                if (isGenPreview) {
                    PreviewGenerateThread previewGenerateThread = new PreviewGenerateThread(vpath, diskName);
                    previewGenerateThread.start();

                    canPreview = true;
                    previewUrl = vpath + diskName.substring(0, diskName.lastIndexOf(".")) + ".html";
                }
            } catch (IOException e) {
                LogUtil.getLog(getClass()).error(e);
            }
        }
        JSONObject json = new JSONObject();
        json.put("id", userPlanAttachment.getId());
        json.put("name", userPlanAttachment.getName());
        json.put("visualPath", vpath);
        json.put("diskName", diskName);
        json.put("fileSize", file.getSize());
        json.put("canPreview", canPreview);
        json.put("previewUrl", previewUrl);
        return new Result<>(json);
    }

    @ApiOperation(value = "列出日程中的附件", notes = "列出日程中的附件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "planId", value = "日程ID", required = true, dataType = "Integer"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/listByPlanId", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> listByPlanId(@RequestParam Integer planId) {
        QueryWrapper<UserPlanAttachment> qw = new QueryWrapper<>();
        qw.eq("plan_id", planId);

        Config cfg = Config.getInstance();

        List<UserPlanAttachment> list = userPlanAttachmentService.list(qw);
        JSONArray arr = (JSONArray)JSONArray.toJSON(list);

        for (Object o : arr) {
            JSONObject json = (JSONObject)o;
            boolean isPreview = false;
            // 判断是否为wps、word文件
            if (FileUtil.isPdfFile(json.getString("diskName"))) {
                if (cfg.getBooleanProperty("canPdfFilePreview")) {
                    isPreview = true;
                }
            } else if (FileUtil.isOfficeFile(json.getString("diskName"))) {
                if (cfg.getBooleanProperty("canOfficeFilePreview")) {
                    isPreview = true;
                }
            }
            if (isPreview) {
                String diskName = json.getString("diskName");
                // 网络环境下，Tomcat方式部署时有时会比较耗时，故在集群时不判断文件是否存在
                boolean isFileExist = true;
                if (!Global.isCluster()) {
                    String s = Global.getRealPath() + json.getString("visualPath") + json.getString("diskName");
                    String htmlfile = s.substring(0, s.lastIndexOf(".")) + ".html";
                    java.io.File fileExist = new java.io.File(htmlfile);
                    isFileExist = fileExist.exists();
                }
                if (isFileExist) {
                    json.put("previewUrl", json.getString("visualPath") + diskName.substring(0, diskName.lastIndexOf(".")) + ".html");
                }
            }
        }

        return new Result<>(arr);
    }

    @ApiOperation(value = "删除日程中的附件", notes = "删除日程中的附件", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long"),
    })
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @ResponseBody
    @RequestMapping(value = "/del", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
    public Result<Object> del(@RequestParam Long id) {
        UserPlanAttachment userPlanAttachment = userPlanAttachmentService.getById(id);
        if (userPlanAttachment.getPlanId() > 0 ) {
            PlanMgr planMgr = new PlanMgr();
            PlanDb planDb = planMgr.getPlanDb(userPlanAttachment.getPlanId());
            if (!new Privilege().isUserPrivValid(request, "admin") && !planDb.getUserName().equals(authUtil.getUserName())) {
                return new Result<>(false, "权限非法");
            }
        }

        boolean re = userPlanAttachmentService.removeById(id);
        if (re) {
            // 删除预览文件
            com.redmoon.oa.Config cfg = com.redmoon.oa.Config.getInstance();
            boolean canOfficeFilePreview = cfg.getBooleanProperty("canOfficeFilePreview");
            boolean canPdfFilePreview = cfg.getBooleanProperty("canPdfFilePreview");
            if (canOfficeFilePreview) {
                if (FileUtil.isOfficeFile(userPlanAttachment.getDiskName())) {
                    PreviewUtil.jacobFileDelete(Global.getRealPath() + userPlanAttachment.getVisualPath() + userPlanAttachment.getDiskName());
                }
            }
            if (canPdfFilePreview) {
                if ("pdf".equalsIgnoreCase(StrUtil.getFileExt(userPlanAttachment.getDiskName()))) {
                    Pdf2Html.del(Global.getRealPath() + userPlanAttachment.getVisualPath() + userPlanAttachment.getDiskName());
                }
            }
        }
        return new Result<>(re);
    }

    @RequestMapping("/download")
    public void download(HttpServletResponse response, @RequestParam Long id) throws IOException, ErrMsgException {
        UserPlanAttachment userPlanAttachment = userPlanAttachmentService.getById(id);
        if (userPlanAttachment.getPlanId() > 0 ) {
            PlanMgr planMgr = new PlanMgr();
            PlanDb planDb = planMgr.getPlanDb(userPlanAttachment.getPlanId());
            if (!new Privilege().isUserPrivValid(request, "admin") && !planDb.getUserName().equals(authUtil.getUserName())) {
               throw new ErrMsgException("权限非法");
            }
        }

//        if (StrUtil.isImage(StrUtil.getFileExt(userPlanAttachment.getDiskName()))) {
//            fileService.preview(response, userPlanAttachment.getVisualPath() + "/" + userPlanAttachment.getDiskName());
//            return;
//        }

        fileService.download(response, userPlanAttachment.getName(), userPlanAttachment.getVisualPath(), userPlanAttachment.getDiskName());
    }
}

